package com.aimei.security.util;

import com.aimei.security.authentication.UserAuthentication;
import com.aimei.security.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * @author xiah
 * date 2018/5/5 16:22
 * 获得当前登录用户的信息
 */
public class UserUtil {
       public static Optional getUserContext() {
              Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
              if ( authentication instanceof UserAuthentication ) {
                     UserAuthentication jwtAuthenticationToken = ( UserAuthentication ) authentication;
                     return Optional.of(jwtAuthenticationToken.getPrincipal());
              }
              return Optional.empty();
       }

       public static String getUserName() {
            User user=(User)  getUserContext().get();
            return  user.getUserName();
       }

}
